package com.android.model.net;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.android.model.entity.res.CreateSessionResult;
import com.android.model.entity.res.CreateTicketResult;
import com.android.model.entity.res.TradePWDVerifyResult;
import com.android.presenter.iview.IResult;
import com.android.util.DateUtils;
import com.android.util.JsonUtil;
import com.android.util.RequestEntityUtils;
import com.android.util.WindowUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.android.BuildConfig;
import com.android.R;
import com.android.app.constant.UrlConstants;
import com.android.model.entity.res.CreateTokenResult;
import com.android.model.entity.res.OrderResponse;
import com.android.model.entity.res.SubmitOrderParamsEntity;
import com.android.model.entity.res.UserInfoResult;
import com.android.model.info.LocalSp;
import com.android.util.AppNecessaryUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;


/**
 * Created by TenFace
 * on 2017/11/13.
 */

public class TradeBizApi {

    public final static int CODE_0x01001A = 0x01001A;
    public final static String MESSAGE_0x01001A = "通用请求错误";

    public final static int CODE_0x02001B = 0x02001B;
    public final static String MESSAGE_0x02001B = "创建账号异常";

    public final static int CODE_0x02002A = 0x02002A;
    public final static String MESSAGE_0x02002A = "账号不存在";

    public final static int CODE_0x02003A = 0x02003A;
    public final static String MESSAGE_0x02003A = "账号被锁定";

    public final static int CODE_0x02004A = 0x02004A;
    public final static String MESSAGE_0x02004A = "账号不是正常状态";

    public final static int CODE_0x03001A = 0x03001A;
    public final static String MESSAGE_0x03001A = "toke错误";

    public final static int CODE_0x03002A = 0x03002A;
    public final static String MESSAGE_0x03002A = "session无效";

    public final static int CODE_0x03003A = 0x03003A;
    public final static String MESSAGE_0x03003A = "session的扩展认证信息无效";

    public final static int CODE_0x05001A = 0x05001A;
    public final static String MESSAGE_0x05001A = "订单ticket无效";


    public final static int CODE_10000 = 10000;
    public final static String MESSAGE_10000 = "系统繁忙，请联系55客服。";

    public final static int CODE_10001 = 10001;
    public final static String MESSAGE_10001 = "该手机已被使用，如已注册请直接登录。";

    public final static int CODE_10002 = 10002;
    public final static String MESSAGE_10002 = "该邮箱已被使用，如已注册请直接登录。";

    public final static int CODE_10003 = 10003;
    public final static String MESSAGE_10003 = "短信验证码不正确，请重新输入。";

    public final static int CODE_10004 = 10004;
    public final static String MESSAGE_10004 = "邮箱验证码不正确，请重新输入。";

    public final static int CODE_10005 = 10005;
    public final static String MESSAGE_10005 = "登录账号或密码不正确，请重新输入。";

    public final static int CODE_10006 = 10006;
    public final static String MESSAGE_10006 = "谷歌秘钥不正确，请重新输入。";

    public final static int CODE_10007 = 10007;
    public final static String MESSAGE_10007 = "登录密码不正确，请重新输入。";

    public final static int CODE_10008 = 10008;
    public final static String MESSAGE_10008 = "谷歌验证码不正确，请重新输入。";

    public final static int CODE_10009 = 10009;
    public final static String MESSAGE_10009 = "新设置密码与原密码相同，请重新输入。";

    public final static int CODE_10010 = 10010;
    public final static String MESSAGE_10010 = "密码必须为8-20位的数字和字母组成。";

    public final static int CODE_10011 = 10011;
    public final static String MESSAGE_10011 = "交易密码必须为6位数字。";

    public final static int CODE_10012 = 10012;
    public final static String MESSAGE_10012 = "邀请码格式不正确。";

    public final static int CODE_10013 = 10013;
    public final static String MESSAGE_10013 = "授权不通过，请重新验证。";

    public final static int CODE_10014 = 10014;
    public final static String MESSAGE_10014 = "用户不存在，请先注册。";

    public final static int CODE_10015 = 10015;
    public final static String MESSAGE_10015 = "账号密码错误次数超过10次，用户被锁定。";

    public final static int CODE_10016 = 10016;
    public final static String MESSAGE_10016 = "未设置交易密码。";

    public final static int CODE_10017 = 10017;
    public final static String MESSAGE_10017 = "密码错误次数过多，请联系客服。";

    public final static int CODE_10018 = 10018;
    public final static String MESSAGE_10018 = "交易密码不正确，请重新输入。";

    public final static int CODE_10019 = 10019;
    public final static String MESSAGE_10019 = "手机号不能为空。";

    public final static int CODE_10020 = 10020;
    public final static String MESSAGE_10020 = "操作类型不正确。";

    public final static int CODE_10021 = 10021;
    public final static String MESSAGE_10021 = "当日验证码获取超过10次。";

    public final static int CODE_10022 = 10022;
    public final static String MESSAGE_10022 = "手机号码不正确。";

    public final static int CODE_10023 = 10023;
    public final static String MESSAGE_10023 = "请求参数异常。";


    public final static String RE_LOGIN = "登录失效，请退出重新登录";
    public final static String TRADE_TOKEN_NULL = "交易token为空";
    public final static String TRADE_PASSWORD_TOKEN_NULL = "sso交易密码token为空";
    public final static String TRADE_ORDER_TOKEN_NULL = "order交易密码token为空";
    public final static String TRADE_SESSION_NULL = "交易session为空";
    public final static String TRADE_ACCOUNT_ID_NULL = "账户ID为空";
    public final static String SECURITY_VERIFY = "安全验证";
    public final static String SECURITY_VERIFY_TIP = "设备更换提示安全问题";
    public final static String NO_SETTING_TRADE_PASSWORD = "没有设置过交易密码";
    public final static String TRADE_PASSWORD_EXPIRED = "交易密码过期";
    public final static String TRADE_PASSWORD_TIMES_TOO_MANY = "交易密码次数过多";
    public final static String TRADE_PASSWORD_TIMES = "密码次数";
    public final static String NULL_ERROR_STATUS = "空错误状态";

    public final static String TOKEN_TYPE_ORDER = "ORDER";
    public final static String TOKEN_TYPE_ASSETS = "ASSETS";
    public final static String TOKEN_TYPE_ACCOUNT = "ACCOUNT";


    public final static String TRADE_TYPE_ORDER = "ORDER";//订单类型
    private final static String GET_DEPOSIT_CASH_URL = "DEPOSIT_CASH_URL";//获取入金url
    private final static String GET_WITH_DRAW_CASH_URL = "WITH_DRAW_CASH_URL";//获取出金url
    private final static String GET_CASH_CHANGE_LIST = "GET_CASH_CHANGE_LIST";//获取资金变动记录

    //开户状态
    public final static String OPEN_ACCOUNT_ONE_STEP = "YG_STEP_0";//开户第一步
    public final static String OPEN_ACCOUNT_TWO_STEP = "YG_STEP_1";//开户第二步
    public final static String OPEN_ACCOUNT_THREE_STEP = "YG_STEP_2";//开户第三步
    public final static String OPEN_ACCOUNT_FOUR_STEP = "YG_STEP_3";//开户第四步
    public final static String OPEN_ACCOUNT_GIVE_STEP = "YG_STEP_4";//开户第五步
    public final static String OPEN_ACCOUNT_PROCESSING = "PROCESSING";//正在处理
    public final static String OPEN_ACCOUNT_INTO_CASH = "YG_STEP_RJ";//入金
    public final static String OPEN_ACCOUNT_COME_TO_END = "YG_STEP_END";//开户结束

    private static final String TAG = "TradeBizApi";
    private static String ip;

    public static TradeBizApi getInstance() {
        return TradeBizApiHolder.instance;
    }

    private static class TradeBizApiHolder {
        static TradeBizApi instance = new TradeBizApi();
    }

//    -------- 直接使用的接口开始---------

    /**
     * 交易验证逻辑
     *
     * @param context       context
     * @param tradePassword 交易密码
     * @param callBack      回调
     */
    public void tradeVerifyBiz(final Context context, final String tradePassword, final IResult<String> callBack) {

        //创建交易token
        createTradeOrderToken(context, new IResult<String>() {
            @Override
            public void success(String tradeToken) {
                LocalSp.getInstance(context).saveOrderTradeToken(tradeToken);
                //交易token创建成功
                //价差是否设置了交易密码
//                Log.e(TAG, "createTradeOrderToken() success");
                isSettingTradePassword(context, new IResult<Boolean>() {
                    @Override
                    public void success(Boolean isSettingTradePassword) {
//                        Log.e(TAG, "isSettingTradePassword() success");

                        if (isSettingTradePassword) {
                            //已经设置过交易密码
                            createTradePasswordToken(context, tradePassword, new IResult<String>() {
                                @Override
                                public void success(String tradePasswordToken) {

//                                    Log.e(TAG, "createTradePasswordToken() success");

                                    //创建交易session
                                    createTradeSession(context, TRADE_TYPE_ORDER, new IResult<String>() {
                                        @Override
                                        public void success(String tradeSession) {
//                                            Log.e(TAG, "createTradeSession() success");
                                            if (callBack != null) {
                                                callBack.success(tradeSession);
                                            }
                                        }

                                        @Override
                                        public void error(Object errorStatus, String msg) {
                                            if (callBack != null) {
                                                callBack.error(errorStatus, msg);
                                            }
                                        }
                                    });

                                }

                                @Override
                                public void error(Object errorStatus, String msg) {
                                    if (callBack != null) {
                                        callBack.error(errorStatus, msg);
                                    }
                                }
                            });
                        } else {
                            //没有设置过交易密码
                            if (callBack != null) {
                                callBack.error(null, MESSAGE_10016);
                            }
                        }
                    }

                    @Override
                    public void error(Object errorStatus, String msg) {
                        if (callBack != null) {
                            callBack.error(errorStatus, msg);
                        }
                    }
                });
            }

            @Override
            public void error(Object errorStatus, String msg) {
                if (callBack != null) {
                    callBack.error(errorStatus, msg);
                }
            }
        });

    }

//    /**
//     * 重置交易密码
//     *
//     * @param context  context
//     * @param password password
//     * @param callBack 回调
//     */
//    public void resetTradePassword(final Context context, final String password, final IResult<String> callBack) {
//
//        createTradeOrderToken(context, new IResult<String>() {
//            @Override
//            public void success(String data) {
//                updateTradePassword(context, password, new IResult<String>() {
//                    @Override
//                    public void success(String data) {
//                        if (callBack != null) {
//                            callBack.success(data);
//                        }
//                    }
//
//                    @Override
//                    public void error(String errorStatus, String msg) {
//                        if (callBack != null) {
//                            callBack.error(null, msg);
//                        }
//                    }
//                });
//            }
//
//            @Override
//            public void error(String errorStatus, String msg) {
//                if (callBack != null) {
//                    callBack.error(null, msg);
//                }
//            }
//        });
//    }

    /**
     * 下单
     *
     * @param context  context
     * @param password password
     * @param callBack callBack
     */
    public void placeOrder(final Context context, final SubmitOrderParamsEntity orderParamsEntity, final String password, final IResult<OrderResponse> callBack) {

        tradeVerifyBiz(context, password, new IResult<String>() {
            @Override
            public void success(final String data) {

                createTicket(context, new IResult<String>() {
                    @Override
                    public void success(String ticket) {
                        if (orderParamsEntity == null) {
                            if (callBack != null) {
                                callBack.error(null, "");
                            }
                            return;
                        }
                        String accountId = LocalSp.getInstance(context).getAccountInfoId();
                        String usTradeSession = LocalSp.getInstance(context).getOrderTradeSession(TRADE_TYPE_ORDER);
//                        String usTradeSession = LocalSp.getInstance(context).getOrderTradeSession(TRADE_TYPE_ORDER);
                        Map<Object, Object> params = new HashMap<>();
                        params.put("accountId", accountId);
                        params.put("ticket", ticket);
                        params.put("orderInfo", orderParamsEntity);
                        Gson g = new Gson();
                        String lastParams = g.toJson(params);
//                        Log.e(TAG, "getTicket() lastParams=" + lastParams);
                        String url = UrlConstants.HOST_HTTPS + UrlConstants.TRADE_CREATE_NEW_ORDER + usTradeSession;
                        OkGo.post(url)
                                .upJson(lastParams)
                                .execute(new StringCallback() {
                                    @Override
                                    public void onSuccess(String s, Call call, Response response) {
//                                        Log.e(TAG, "s=" + s);
                                        OrderResponse orderResponse = JsonUtil.parseJsonToBean(s, OrderResponse.class);
                                        if (orderResponse != null) {
//                                            if (orderResponse.getStatus().equals(CommonType.STATUS_TYPE_SUCCESS)) {
                                            if (callBack != null) {
                                                callBack.success(orderResponse);
                                            }
//                                            } else {
//                                                if (callBack != null) {
//                                                    callBack.error(null, orderResponse.getMsg());
//                                                }
//                                            }
                                        } else {
                                            if (callBack != null) {
                                                callBack.error(null, "");
                                            }
                                        }
                                    }

                                    @Override
                                    public void onError(Call call, Response response, Exception e) {
                                        super.onError(call, response, e);
                                        if (callBack != null) {
                                            callBack.error(null, context.getResources().getString(R.string.server_error));
                                        }
                                    }
                                });
                    }

                    @Override
                    public void error(Object errorStatus, String msg) {
                        if (callBack != null) {
                            callBack.error(errorStatus, msg);
                        }
                    }
                });
            }

            @Override
            public void error(Object errorStatus, String msg) {
                if (callBack != null) {
                    callBack.error(errorStatus, msg);
                }
            }
        });

    }

//    /**
//     * 获取入金url
//     *
//     * @param context  context
//     * @param callback callback
//     */
//    public void getDepositCashUrl(Context context, final IResult<UrlEntity> callback) {
//        getCashUrl(context, GET_DEPOSIT_CASH_URL, callback);
//    }
//
//    /**
//     * 获取出金url
//     *
//     * @param context  context
//     * @param callback callback回调
//     */
//    public void getWithDrawCashUrl(Context context, IResult<UrlEntity> callback) {
//        getCashUrl(context, GET_WITH_DRAW_CASH_URL, callback);
//    }
//
//    /**
//     * 获取资金变动url
//     *
//     * @param context  context
//     * @param callback callBack
//     */
//    public void getCashChangeList(final Context context, final IResult<String> callback) {
//
//        createTradeOrderToken(context, new IResult<String>() {
//            @Override
//            public void success(String tradeToken) {
//                String url = CommonURL.PUBLIC_SERVICE_TRADE_LINE + CommonURL.GET_CASH_CHANGE_LIST;
//                String params = "\"" + tradeToken + "\"";
//                OkGo.post(url).upJson(params).execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(String s, Call call, Response response) {
//                        callback.success(s);
//                    }
//
//                    @Override
//                    public void onError(Call call, Response response, Exception e) {
//                        super.onError(call, response, e);
//                        if (callback != null) {
//                            callback.error(NULL_ERROR_STATUS, "");
//                        }
//                    }
//                });
//            }
//
//            @Override
//            public void error(String errorStatus, String msg) {
//                if (callback != null) {
//                    callback.error(null, context.getResources().getString(R.string.server_error));
//                }
//            }
//        });
//
//
//    }
//
//    /**
//     * 获取出入金记录
//     *
//     * @param context     context
//     * @param currentPage 当前页数
//     * @param requestNum  请求数据条数
//     * @param callBack    回调
//     */
//    public void getAccessGoldRecordActivity(Context context, final int currentPage, final int requestNum, final IResult<List<AccessGoldRecordEntity>> callBack) {
//
//
//        createTradeOrderToken(context, new IResult<String>() {
//            @Override
//            public void success(String tradeToken) {
//                String url = CommonURL.PUBLIC_SERVICE_TRADE_LINE + CommonURL.TRADE_ACCESS_GOLD_RECORD;
////                ArrayList<Object> params = new ArrayList<>();
////                params.add(tradeToken.replaceAll("\"", ""));
//////                params.add(String.valueOf(currentPage));
//////                params.add(requestNum);
////                Gson g = new Gson();
////                String lastParams = g.toJson(params);
//                String lastParams = "\"" + tradeToken + "\"";
////                Log.e(TAG, "lastParams=" + lastParams);
//                OkGo.post(url).upJson(lastParams).execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(String s, Call call, Response response) {
//                        GoldRecordEntityResponse goldRecordEntityResponse = JsonUtil.parseJsonToBean(s, GoldRecordEntityResponse.class);
//                        if (goldRecordEntityResponse != null) {
//                            if (goldRecordEntityResponse.getStatus().equals(CommonType.STATUS_TYPE_SUCCESS)) {
//                                if (callBack != null) {
//                                    callBack.success(goldRecordEntityResponse.getData());
//                                }
//                            } else {
//                                if (callBack != null) {
//                                    callBack.error(null, goldRecordEntityResponse.getMsg());
//                                }
//                            }
//                        } else {
//                            if (callBack != null) {
//                                callBack.error(null, "");
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onError(Call call, Response response, Exception e) {
//                        super.onError(call, response, e);
//                        if (callBack != null) {
//                            callBack.error(NULL_ERROR_STATUS, "");
//                        }
//                    }
//                });
//            }
//
//            @Override
//            public void error(String errorStatus, String msg) {
//                if (callBack != null) {
//                    callBack.error(errorStatus, msg);
//                }
//            }
//        });
//    }

//    /**
//     * 撤销订单
//     *
//     * @param context  context
//     * @param password 交易密码
//     * @param orderId  订单id
//     * @param callBack 回调
//     */
//    public void revokeOrder(final Context context, String password, final String orderId, final IResult<String> callBack) {
//
//        tradeVerifyBiz(context, password, new IResult<String>() {
//            @Override
//            public void success(String data) {
//                String passwordToken = LocalSp.getInstance(context).getTradePasswordToken();
//                String session = LocalSp.getInstance(context).getSession(TRADE_TYPE_ORDER);
//                OkGo.post(CommonURL.PUBLIC_SERVICE_TRADE_LINE + CommonURL.TRADE_QUERY_CANCEL_ORDER)
//                        .upJson("[" + "\"" + passwordToken + "\",\"" + session + "\",\"" + orderId + "\"" + "]")
//                        .execute(new StringCallback() {
//                            @Override
//                            public void onSuccess(String s, Call call, Response response) {
////                                Log.e(TAG, "revokeOrder s=" + s);
//                                BaseResponse baseResponse = JsonUtil.parseJsonToBean(s, BaseResponse.class);
//                                if (baseResponse.getStatus().equals(CommonType.STATUS_TYPE_SUCCESS)) {
//                                    if (callBack != null) {
//                                        callBack.success(baseResponse.getStatus());
//                                    }
//                                } else {
//                                    if (callBack != null) {
//                                        callBack.error(null, baseResponse.getMsg());
//                                    }
//                                }
//                            }
//
//                            @Override
//                            public void onError(Call call, Response response, Exception e) {
//                                super.onError(call, response, e);
//                                if (callBack != null) {
//                                    callBack.error(null, context.getResources().getString(R.string.server_error));
//                                }
//                            }
//                        });
//            }
//
//            @Override
//            public void error(String errorStatus, String msg) {
//                if (callBack != null) {
//                    callBack.error(errorStatus, msg);
//                }
//            }
//        });
//    }


//    /**
//     * 获取用户交易账户信息
//     *
//     * @param context  context
//     * @param callback callback 回调
//     */
//    public void getUserTradeAccountInfo(final Context context, final IResult<TradeAccountInfo> callback) {
//
//        createTradeOrderToken(context, new IResult<String>() {
//            @Override
//            public void success(String tradeToken) {
//                String url = CommonURL.PUBLIC_SERVICE_TRADE_LINE + CommonURL.TRADE_ACCOUNT_INFO;
//                OkGo.post(url)
//                        .upJson("\"" + tradeToken + "\"")
//                        .execute(new StringCallback() {
//                            @Override
//                            public void onSuccess(String s, Call call, Response response) {
//                                TradeAccountInfoResponse tradeAccountInfoResponse = JsonUtil.parseJsonToBean(s, TradeAccountInfoResponse.class);
//                                if (tradeAccountInfoResponse != null) {
//                                    if (CommonType.STATUS_TYPE_SUCCESS.equals(tradeAccountInfoResponse.getStatus())) {
//                                        //成功
//                                        if (callback != null) {
//                                            callback.success(tradeAccountInfoResponse.data);
//                                        }
//                                    } else {
//                                        //失败
//                                        if (callback != null) {
//                                            callback.error(null, tradeAccountInfoResponse.getMsg());
//                                        }
//                                    }
//                                } else {
//                                    if (callback != null) {
//                                        callback.error(null, context.getResources().getString(R.string.server_error));
//                                    }
//                                }
//                            }
//
//                            @Override
//                            public void onError(Call call, Response response, Exception e) {
//                                super.onError(call, response, e);
//                                if (callback != null) {
//                                    callback.error(null, context.getResources().getString(R.string.server_error));
//                                }
//                            }
//                        });
//            }
//
//            @Override
//            public void error(String errorStatus, String msg) {
//                if (callback != null) {
//                    callback.error(errorStatus, msg);
//                }
//            }
//        });
//    }

//    /**
//     * 获取ip
//     */
//    public void getIp() {
//
//        if (!TextUtils.isEmpty(ip)) {
//            return;
//        }
//        String url = CommonURL.GET_CURRENT_IP;
//        OkGo.post(url)
//                .execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(String s, Call call, Response response) {
//                        try {
//                            IpEntity ipEntity = JsonUtil.parseJsonToBean(s, IpEntity.class);
//                            if (ipEntity != null) {
//                                ip = ipEntity.v;
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//
//                    @Override
//                    public void onError(Call call, Response response, Exception e) {
//                        super.onError(call, response, e);
//                    }
//                });
//    }
//    -------- 直接使用的接口结束---------


//    /**
//     * 获取资金url
//     *
//     * @param context       context
//     * @param GET_CASH_TYPE 获取资金类型
//     * @param callback      callback 回调
//     */
//    private void getCashUrl(final Context context, final String GET_CASH_TYPE, final IResult<UrlEntity> callback) {
//
//        createTradeOrderToken(context, new IResult<String>() {
//            @Override
//            public void success(String tradeToken) {
//                String url;
//                if (GET_CASH_TYPE.equals(GET_DEPOSIT_CASH_URL)) {
//                    //入金url
//                    url = CommonURL.PUBLIC_SERVICE_TRADE_LINE + CommonURL.GET_DEPOSIT_CASH_URL;
//                } else {
//                    //出金url
//                    url = CommonURL.PUBLIC_SERVICE_TRADE_LINE + CommonURL.GET_WITH_DRAW_CASH_URL;
//                }
//                String params = "\"" + tradeToken + "\"";
//                OkGo.post(url).upJson(params).execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(String s, Call call, Response response) {
//
//                        UrlEntityResponse urlEntityResponse = JsonUtil.parseJsonToBean(s, UrlEntityResponse.class);
//                        if (urlEntityResponse != null) {
//                            if (urlEntityResponse.getStatus().equals(CommonType.STATUS_TYPE_SUCCESS)) {
//                                if (callback != null) {
//                                    callback.success(urlEntityResponse.getData());
//                                }
//                            } else {
//                                if (callback != null) {
//                                    callback.error(null, urlEntityResponse.getMsg());
//                                }
//                            }
//                        } else {
//                            if (callback != null) {
//                                callback.error(NULL_ERROR_STATUS, "");
//                            }
//                        }
//
//                    }
//
//                    @Override
//                    public void onError(Call call, Response response, Exception e) {
//                        super.onError(call, response, e);
//                        if (callback != null) {
//                            callback.error(NULL_ERROR_STATUS, "");
//                        }
//                    }
//                });
//            }
//
//            @Override
//            public void error(String errorStatus, String msg) {
//                if (callback != null) {
//                    callback.error(null, context.getResources().getString(R.string.server_error));
//                }
//            }
//        });
//    }

    /**
     * 创建交易token
     *
     * @param context  context
     * @param callBack 回调
     */
    public void createTradeOrderToken(final Context context, final IResult<String> callBack) {

        String accountToken = LocalSp.getInstance(context).getAccountToken();//用户登录之后的account token
        if (TextUtils.isEmpty(accountToken)) {
            //请登录
            if (callBack != null) {
                callBack.error(null, RE_LOGIN);
            }
            return;
        }
        if (!AppNecessaryUtils.checkNetConnectionState(context)) {
            if (callBack != null) {
                callBack.error(null, context.getResources().getString(R.string.internet_error));
            }
            return;
        }
        //先判断交易token是否存在 并且没有过期
        String tradeToken = LocalSp.getInstance(context).getOrderTradeToken();
        long tradeTokenExpiredTime = LocalSp.getInstance(context).getOrderTradeTokenExpiredTime();
        if (!TextUtils.isEmpty(tradeToken) && tradeTokenExpiredTime != LocalSp.DEFAULT_VALUE) {
            //如果tradeToken 没有过期直接返回
            long currentTime = DateUtils.getCurrentTimeAddAMinute();
            if (tradeTokenExpiredTime > currentTime) {
                if (callBack != null) {
                    callBack.success(tradeToken);
                }
                return;
            }
        }
        RequestEntityUtils.OsEntity osEntity = getOsEntity(context);

        String accountId = LocalSp.getInstance(context).getAccountInfoId();

        Map<Object, Object> params = new HashMap<>();
        params.put("accountId", accountId);
        params.put("tokenType", TOKEN_TYPE_ORDER);
        Gson g = new Gson();
        String lastParams = g.toJson(params);
//        Log.e(TAG, "lastParams=" + lastParams);

        String url = UrlConstants.HOST_HTTPS + UrlConstants.TRADE_CREATE_TOKEN + accountToken;
        OkGo.post(url)
                .upJson(lastParams)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
//                        Log.e(TAG, "createTradeOrderToken s=" + s);
                        try {
                            CreateTokenResult resultEntity = JsonUtil.parseJsonToBean(s, CreateTokenResult.class);
                            if (resultEntity != null) {
//                                if (resultEntity.getStatus().equals(CommonType.STATUS_TYPE_SUCCESS)) {
                                if (resultEntity.getValue() != null) {
                                    //保存创建的token 与 过期时间
                                    LocalSp.getInstance(context).saveOrderTradeToken(resultEntity.getValue());
                                    LocalSp.getInstance(context).saveOrderTradeTokenExpiredTime((int) resultEntity.getExpiredAt());
                                }
                                //签发成功
                                if (callBack != null) {
                                    callBack.success(resultEntity.getValue());
                                }
//                                } else {
//                                    //签发失败
//                                    if (callBack != null) {
//                                        callBack.error(null, resultEntity.getMsg());
//                                    }
//                                }
                            } else {
                                if (callBack != null) {
                                    callBack.error(NULL_ERROR_STATUS, null);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (callBack != null) {
                            callBack.error(null, context.getResources().getString(R.string.server_error));
                        }
                    }
                });
    }

    /**
     * 判断是否设置了交易密码
     *
     * @param context  context
     * @param callBack callBack
     */
    public void isSettingTradePassword(final Context context, final IResult<Boolean> callBack) {

        String ssoToken = LocalSp.getInstance(context).getSSOToken();
        if (TextUtils.isEmpty(ssoToken)) {
            if (callBack != null) {
                callBack.error(null, RE_LOGIN);
            }
            return;
        }
        boolean isSettingTradePassword = LocalSp.getInstance(context).getIsSettingTradePassword();
        if (isSettingTradePassword) {
            //已经设置过交易密码
            if (callBack != null) {
                callBack.success(true);
            }
            return;
        }

        String url = UrlConstants.HOST_HTTPS + UrlConstants.USER_QUERY_INFO;

//        Log.e(TAG, "lastParams=" + lastParams);
        OkGo.post(url)
                .headers("token", ssoToken)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            Log.e(TAG, "isSettingTradePassword s=" + s);
                            UserInfoResult resultResponse = JsonUtil.parseJsonToBean(s, UserInfoResult.class);
                            if (resultResponse != null) {
//                                if (resultResponse.getStatus().equals(CommonType.STATUS_TYPE_SUCCESS)) {
                                LocalSp.getInstance(context).saveIsSettingTradePassword(resultResponse.isIsSetTradePasswrod());
                                if (callBack != null) {
                                    callBack.success(resultResponse.isIsSetTradePasswrod());
                                }
//                                } else {
//                                    if (callBack != null) {
//                                        callBack.error(null, resultResponse.getMsg());
//                                    }
//                                }
                            } else {
                                if (callBack != null) {
                                    callBack.error(NULL_ERROR_STATUS, null);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (callBack != null) {
                            callBack.error(null, context.getResources().getString(R.string.server_error));
                        }
                    }
                });

    }


    /**
     * 创建交易密码token
     *
     * @param context       context
     * @param tradePassword 交易密码
     * @param callBack      回调
     */
    public void createTradePasswordToken(final Context context, String tradePassword, final IResult<String> callBack) {
        String ssoToken = LocalSp.getInstance(context).getSSOToken();

        if (TextUtils.isEmpty(ssoToken)) {
            if (callBack != null) {
                callBack.error(null, RE_LOGIN);
            }
            return;
        }
        //判断交易token是否存在 并且没有过期
        String tradePasswordToken = LocalSp.getInstance(context).getSSOTradeToken();
        long tradePasswordExpiredTime = LocalSp.getInstance(context).getSSOTradeTokenExpiredTime();
        if (!TextUtils.isEmpty(tradePasswordToken) && tradePasswordExpiredTime != LocalSp.DEFAULT_VALUE) {
            long currentTimeAddAMinute = DateUtils.getCurrentTimeAddAMinute();
            if (tradePasswordExpiredTime > currentTimeAddAMinute) {
                if (callBack != null) {
                    callBack.success(tradePasswordToken);
                }
                return;
            }
        }

        // 交易密码为空，弹出窗体
        if (TextUtils.isEmpty(tradePassword)) {
            if (callBack != null) {
                callBack.error(null, TRADE_PASSWORD_EXPIRED);
            }
            return;
        }


        Map<Object, Object> params = new HashMap<>();
//        params.add(ssoToken);
        params.put("password", tradePassword);
        Gson g = new Gson();
        String lastParams = g.toJson(params);
        Log.e(TAG, "lastParams=" + lastParams);
        String url = UrlConstants.HOST_HTTPS + UrlConstants.USER_TRADE_PWD_VERIFY;
        OkGo.post(url)
                .headers("Content-Type", "application/json;charset=utf-8")
                .headers("token", ssoToken)
                .upJson(lastParams)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.e(TAG, "createTradePasswordToken s=" + s);
                        TradePWDVerifyResult resultEntity = JsonUtil.parseJsonToBean(s, TradePWDVerifyResult.class);
                        if (resultEntity != null) {
//                            String status = resultEntity.getStatus();
//                            if (!TextUtils.isEmpty(status)) {
//                                if (status.equals(CommonType.STATUS_TYPE_SUCCESS)) {

                            switch (resultEntity.getCode()) {
                                case CODE_10016:
                                    callBack.error(CODE_10016, MESSAGE_10016);
                                    break;
                                case CODE_10017:
                                    callBack.error(CODE_10017, MESSAGE_10017);
                                    break;
                                case CODE_10018:
                                    callBack.error(CODE_10018, MESSAGE_10018);
                                    break;
                                default:
                                    if (resultEntity.getToken() != null) {
                                        LocalSp.getInstance(context).saveSSOTradeToken(resultEntity.getToken());
                                        LocalSp.getInstance(context).saveSSOTradeExpiredTime(resultEntity.getExpiredTime());
                                    }
                                    //签发成功
                                    if (callBack != null) {
                                        callBack.success(resultEntity.getToken());
                                    }
                            }


//                                } else if (status.equals(CommonType.STATUS_TYPE_WARNING_ONE)) {
//                                    //交易密码次数
//                                    if (callBack != null) {
//                                        callBack.error(TRADE_PASSWORD_TIMES, resultEntity.getMsg());
//                                    }
//                                } else if (status.equals(CommonType.STATUS_TYPE_WARNING_TWO)) {
//                                    //密码次数过多
//                                    if (callBack != null) {
//                                        callBack.error(TRADE_PASSWORD_TIMES_TOO_MANY, resultEntity.getMsg());
//                                    }
//                                } else {
//                                    //签发失败
//                                    if (callBack != null) {
//                                        callBack.error(null, resultEntity.getMsg());
//                                    }
//                                }
//                            } else {
//                                if (callBack != null) {
//                                    callBack.error(NULL_ERROR_STATUS, null);
//                                }
//                            }
                        } else {
                            if (callBack != null) {
                                callBack.error(NULL_ERROR_STATUS, null);
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (callBack != null) {
                            callBack.error(null, context.getResources().getString(R.string.server_error));
                        }
                    }
                });

    }

    /**
     * 创建交易session
     *
     * @param context   context
     * @param tradeType 交易类型
     * @param callBack  回调
     */
    public void createTradeSession(final Context context, final String tradeType, final IResult<String> callBack) {

        String ssoTradeToken = LocalSp.getInstance(context).getSSOTradeToken();
        if (TextUtils.isEmpty(ssoTradeToken)) {
            //sso交易token为空
            if (callBack != null) {
                callBack.error(null, TRADE_PASSWORD_TOKEN_NULL);
            }
            return;
        }

        String orderTradeToken = LocalSp.getInstance(context).getOrderTradeToken();
        if (TextUtils.isEmpty(orderTradeToken)) {
            //order交易token为空
            if (callBack != null) {
                callBack.error(null, TRADE_ORDER_TOKEN_NULL);
            }
            return;
        }

        String tradeSession = LocalSp.getInstance(context).getOrderTradeSession(tradeType);
        long sessionExpiredTime = LocalSp.getInstance(context).getSessionExpiredTime(tradeType);
        if (!TextUtils.isEmpty(tradeSession) && sessionExpiredTime != LocalSp.DEFAULT_VALUE) {
            long currentTimeAddAMinute = DateUtils.getCurrentTimeAddAMinute();
            if (sessionExpiredTime > currentTimeAddAMinute) {
                //没有过期
                if (callBack != null) {
                    callBack.success(tradeSession);
                }
                return;
            }
        }

        String accountId = LocalSp.getInstance(context).getAccountInfoId();

        Map<Object, Object> params = new HashMap<>();
        params.put("accountId", accountId);
        params.put("extension", ssoTradeToken);
        Gson g = new Gson();
        String lastParams = g.toJson(params);
        Log.e(TAG, "lastParams=" + lastParams);
        final String url = UrlConstants.HOST_HTTPS + UrlConstants.TRADE_CREATE_SESSION + orderTradeToken;
        OkGo.post(url)
                .upJson(lastParams)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.e(TAG, "createTradeSession s=" + s);
                        CreateSessionResult resultEntity = JsonUtil.parseJsonToBean(s, CreateSessionResult.class);
//                        UrlEntityResponse urlResponse = JsonUtil.parseJsonToBean(s, UrlEntityResponse.class);
//                        if (urlResponse != null) {
//                            //安全验证
//                            if (urlResponse.getStatus().equals(CommonType.STATUS_TYPE_WARNING_FORBINDDEN)) {
//                                if (callBack != null) {
//                                    //安全验证
////                                    "data":{"url":"https://web-uat.16financial.net/v1/web/auth?websession=2cc3f947-bb88-497a-9aba-200b99975b03","status":"OPENED"}}
////                                    data中可能有多种状态信息，之后可能会修改
//                                    callBack.error(SECURITY_VERIFY, urlResponse.getData().getUrl());
//                                }
//                            }
//                        }

                        if (resultEntity != null) {
//                            String status = resultEntity.getStatus();
//                            if (status.equals(CommonType.STATUS_TYPE_SUCCESS)) {
                            //成功
                            //保存session信息 与session过期时间
                            if (resultEntity.getValue() != null) {
                                LocalSp.getInstance(context).saveOrderTradeSession(resultEntity.getValue(), tradeType);
                                LocalSp.getInstance(context).saveSessionExpiredTime(tradeType, resultEntity.getExpiredAt());
                            }
                            if (callBack != null) {
                                callBack.success(resultEntity.getValue());
                            }
//                            } else {
//                                if (callBack != null) {
//                                    callBack.error(null, resultEntity.getMsg());
//                                }
//                            }
                        }

                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (callBack != null) {
                            callBack.error(null, context.getResources().getString(R.string.server_error));
                        }
                    }
                });

    }

//    /**
//     * 重新创建交易session
//     *
//     * @param context     context
//     * @param sessionType session类型
//     * @param callBack    回调
//     */
//    public void reNewTradeSession(final Context context, String sessionType, final IResult<String> callBack) {
//        String tradePasswordToken = LocalSp.getInstance(context).getTradePasswordToken();
//        if (TextUtils.isEmpty(tradePasswordToken)) {
//            if (callBack != null) {
//                callBack.error(null, TRADE_PASSWORD_TOKEN_NULL);
//            }
//            return;
//        }
//        String tradeOrderSession = LocalSp.getInstance(context).getSession(sessionType);
//        if (TextUtils.isEmpty(tradeOrderSession)) {
//            if (callBack != null) {
//                callBack.error(null, TRADE_SESSION_NULL);
//            }
//            return;
//        }
//
//        ArrayList<Object> params = new ArrayList<>();
//        params.add(tradePasswordToken);
//        params.add(tradeOrderSession);
//        params.add(sessionType);
//        Gson g = new Gson();
//        String lastParams = g.toJson(params);
//        Log.e(TAG, "lastParams=" + lastParams);
//        final String url = CommonURL.PUBLIC_SERVICE_TRADE_LINE + CommonURL.CREATE_TRADE_SESSION;
//        OkGo.post(url)
//                .upJson(lastParams)
//                .execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(String s, Call call, Response response) {
//                        Log.e(TAG, "s=" + s);
//                    }
//
//                    @Override
//                    public void onError(Call call, Response response, Exception e) {
//                        super.onError(call, response, e);
//                        if (callBack != null) {
//                            callBack.error(null, context.getResources().getString(R.string.server_error));
//                        }
//                    }
//                });
//
//
//    }

//    /**
//     * 更新交易密码
//     *
//     * @param context  context
//     * @param password password
//     * @param callBack 回调
//     */
//    private void updateTradePassword(final Context context, String password, final IResult<String> callBack) {
//        String tradeToken = LocalSp.getInstance(context).getTradeToken();
//        if (TextUtils.isEmpty(tradeToken)) {
//            if (callBack != null) {
//                callBack.error(null, TRADE_TOKEN_NULL);
//            }
//            return;
//        }
//
//        ArrayList<Object> params = new ArrayList<>();
//        params.add(tradeToken);
//        params.add(password);
//        Gson g = new Gson();
//        String lastParams = g.toJson(params);
//        Log.e(TAG, "lastParams=" + lastParams);
//        final String url = CommonURL.PUBLIC_SERVICE_TRADE_LINE + CommonURL.UPDATE_TRADE_PASSWORD;
//        OkGo.post(url)
//                .upJson(lastParams)
//                .execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(String s, Call call, Response response) {
//                        Log.e(TAG, "s=" + s);
//                        BaseResponse result = JsonUtil.parseJsonToBean(s, BaseResponse.class);
//                        if (result != null) {
//                            if (result.getStatus().equals(CommonType.STATUS_TYPE_SUCCESS)) {
//                                if (callBack != null) {
//                                    callBack.success(s);
//                                }
//                            } else {
//                                if (callBack != null) {
//                                    callBack.error(null, result.getMsg());
//                                }
//                            }
//                        }
//                    }
//
//                    @Override
//                    public void onError(Call call, Response response, Exception e) {
//                        super.onError(call, response, e);
//                        if (callBack != null) {
//                            callBack.error(null, context.getResources().getString(R.string.server_error));
//                        }
//                    }
//                });
//    }

    /**
     * 创建ticket
     *
     * @param context  context
     * @param callback callback 回调
     */
    public void createTicket(final Context context, final IResult<String> callback) {

        String orderTradeSession = LocalSp.getInstance(context).getOrderTradeSession(TRADE_TYPE_ORDER);
        String accountId = LocalSp.getInstance(context).getAccountInfoId();
        if (TextUtils.isEmpty(accountId)) {
            if (callback != null) {
                callback.error(null, TRADE_ACCOUNT_ID_NULL);
            }
            return;
        }
        if (TextUtils.isEmpty(orderTradeSession)) {
            if (callback != null) {
                callback.error(null, TRADE_SESSION_NULL);
            }
            return;
        }
//        Map<Object, Object> params = new HashMap<>();
//        params.put("accountId", accountId);
//        Gson g = new Gson();
//        String lastParams = g.toJson(params);
        List<String> lastParams = new ArrayList<>();
        lastParams.add(accountId);

        Log.e(TAG, "getTicket() lastParams=" + lastParams);
        String url = UrlConstants.HOST_HTTPS + UrlConstants.TRADE_CREATE_TICKET + orderTradeSession;
        OkGo.post(url)
                .addUrlParams("accountId", lastParams)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.e(TAG, "getTicket s=" + s);
                        CreateTicketResult createTicketResult = JsonUtil.parseJsonToBean(s, CreateTicketResult.class);
                        if (createTicketResult != null) {
//                            if (createTicketResult.getStatus().equals(CommonType.STATUS_TYPE_SUCCESS)) {
                            if (callback != null) {
                                callback.success(createTicketResult.getValue());
                            }
//                            }
//                            else {
//                                if (callback != null) {
//                                    callback.error(null, createTicketResult.getMsg());
//                                }
//                            }
                        } else {
                            if (callback != null) {
                                callback.error(null, "");
                            }
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (callback != null) {
                            callback.error(null, context.getResources().getString(R.string.server_error));
                        }
                    }
                });

    }

//    /**
//     * 检查开户是否成功
//     *
//     * @param context  context
//     * @param callBack 回调
//     */
//    public void checkingAccountIsSuccess(final Context context, final IResult<Boolean> callBack) {
//
//        //1.判断本地是否开户成功 如果本地有从本地取出来
//        //2.本地开户失败 从网络获取开户状态
//        if (LocalSp.getInstance(context).getAccountState()) {
//            // 已经开户
//            if (callBack != null) {
//                callBack.success(true);
//            }
//        } else {
//            //没开户 从网络在判断一次
//
//            if (!AppNecessaryUtils.checkNetConnectionState(context)) {
//                if (callBack != null) {
//                    ToastUtil.show(context, context.getResources().getString(R.string.internet_error));
//                    callBack.success(false);
//                }
//                return;
//            }
//
//            String ssoToken = GalaxyMainActivity.userPreferences.getString(CommonType.SP_USER_TOKEN, null);
//            if (!TextUtils.isEmpty(ssoToken)) {
//                OkGo.post(CommonURL.PUBLIC_SERVICE_LINE + CommonURL.TRADE_GET_KH_STATUS)
//                        .upJson(ssoToken)
//                        .execute(new StringCallback() {
//                            @Override
//                            public void onSuccess(String s, Call call, Response response) {
//                                try {
//                                    UserCommon userCommon = JsonUtil.parseJsonToBean(s, UserCommon.class);
//                                    if (userCommon != null && userCommon.getStatus() != null && userCommon.getStatus().equals(CommonType.STATUS_TYPE_SUCCESS)) {
//                                        String data = userCommon.getData();
//                                        if (data.equals(OPEN_ACCOUNT_COME_TO_END)) {
//                                            //已经开户状态
//                                            if (callBack != null) {
//                                                callBack.success(true);
//                                            }
//                                            LocalSp.getInstance(context).saveAccountState(true);
//                                        } else {
//                                            //还没开户状态
//                                            if (callBack != null) {
//                                                callBack.success(false);
//                                            }
//                                            LocalSp.getInstance(context).saveAccountState(false);
//                                        }
//
//                                    }
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                            }
//
//                            @Override
//                            public void onError(Call call, Response response, Exception e) {
//                                super.onError(call, response, e);
//
//                                if (callBack != null) {
//                                    callBack.success(false);
//                                }
//
//                            }
//                        });
//            } else {
//
//                if (callBack != null) {
//                    callBack.success(false);
//                }
//
//            }
//
//        }
//    }

//    /**
//     * 获取开户状态
//     *
//     * @param context  context
//     * @param callback 回调
//     */
//    public void getAccountState(final Context context, final IResult<String> callback) {
//
//        String ssoToken = GalaxyMainActivity.userPreferences.getString(CommonType.SP_USER_TOKEN, null);
//        if (!TextUtils.isEmpty(ssoToken)) {
//            OkGo.post(CommonURL.PUBLIC_SERVICE_LINE + CommonURL.TRADE_GET_KH_STATUS)
//                    .upJson(ssoToken)
//                    .execute(new StringCallback() {
//                        @Override
//                        public void onSuccess(String s, Call call, Response response) {
//                            try {
//                                UserCommon userCommon = JsonUtil.parseJsonToBean(s, UserCommon.class);
//                                if (userCommon != null && userCommon.getStatus() != null && userCommon.getStatus().equals(CommonType.STATUS_TYPE_SUCCESS)) {
//                                    String data = userCommon.getData();
//                                    if (callback != null) {
//                                        callback.success(data);
//                                    }
//                                } else {
//                                    if (callback != null) {
//                                        callback.error("", context.getResources().getString(R.string.server_error));
//                                    }
//                                }
//                            } catch (Exception e) {
//                                e.printStackTrace();
//                            }
//                        }
//
//                        @Override
//                        public void onError(Call call, Response response, Exception e) {
//                            super.onError(call, response, e);
//
//                            try {
//                                if (callback != null) {
//                                    callback.error("", context.getResources().getString(R.string.server_error));
//                                }
//                            } catch (Resources.NotFoundException e1) {
//                                e1.printStackTrace();
//                            }
//
//                        }
//                    });
//        } else {
//            if (callback != null) {
//                callback.error("", RE_LOGIN);
//            }
//        }
//    }


    /**
     * 获取手机信息
     *
     * @param context context
     * @return 手机信息
     */
    private RequestEntityUtils.OsEntity getOsEntity(Context context) {
        RequestEntityUtils.OsEntity osEntity = new RequestEntityUtils.OsEntity();
        osEntity.osType = "ANDROID";
        osEntity.osVersion = android.os.Build.VERSION.RELEASE;
        osEntity.resolution = WindowUtils.getScreenWidth(context) + "*" + WindowUtils.getScreenHeight(context);
        osEntity.appVersion = BuildConfig.VERSION_CODE + "";
        String machineImEi = AppNecessaryUtils.getUUId(context);

        if (!TextUtils.isEmpty(machineImEi)) {
            osEntity.deviceId = machineImEi;
        }
        if (!TextUtils.isEmpty(ip)) {
            osEntity.ip = ip;
        } else {
            String localIpAddress = AppNecessaryUtils.getLocalIpAddress();
            if (!TextUtils.isEmpty(localIpAddress)) {
                osEntity.ip = localIpAddress;
            }
        }

        return osEntity;
    }


}
